import {ChangeDetectionStrategy, Component, EventEmitter, OnInit} from '@angular/core';
import {OrderService} from '../../service/order.service';
import {ActivatedRoute, Router} from '@angular/router';
import {Observable} from 'rxjs';
import {ProductVariant} from '../../domain';
import {filter, map, switchMap} from 'rxjs/operators';
import {DialogService} from '../../../dialog/services/dialog.service';
import {ProductVariantDialogComponent} from '../product-variant-dialog/product-variant-dialog.component';

@Component({
  selector: 'app-product-container',
  templateUrl: './product-container.component.html',
  styleUrls: ['./product-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductContainerComponent implements OnInit {
  variants$: Observable<ProductVariant[]>;
  selectedIndex = 0;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private service: OrderService,
    private dialogService: DialogService
  ) {
  }

  ngOnInit(): void {
    const productId$ = this.route.paramMap.pipe(
      filter(params => params.has('productId')),
      map(params => params.get('productId'))
    );
    this.variants$ = productId$.pipe(
      switchMap(productId => this.service.getProductVariantsByProductId(productId))
    );
  }

  handleDirectBuy(productVariants: ProductVariant[]): void {

  }

  handleGroupBuy(productVariants: ProductVariant[]): void {
    const top = 40;
    // Subject 既是 Observable 也是一个 Observer
    // Subject 可以 next(xxx), 也可以 subscribe
    // Behavior Subject 是 Subject 的一种特殊形式, 可以记住Subject最近的值
    const formSubmitted = new EventEmitter();
    formSubmitted.subscribe(ev => {
      console.log(ev);
      this.dialogService.saveData(ev);
      this.router.navigate(['/orders/confirm']);
    });

    const selected = new EventEmitter();
    selected.subscribe(ev => {
      console.log(ev);
      this.selectedIndex = ev;
    });

    this.dialogService.open(ProductVariantDialogComponent, {
      inputs: {
        variants: productVariants,
        selectedVariantIndex: this.selectedIndex
      },
      outputs: {
        formSubmitted,
        selected
      },
      position: {
        top: `${top}%`,
        left: '0',
        width: '100%',
        height: `${100 - top}%`
      }
    });
  }
}
